import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from sc.lib.base import BaseController, render

from sc.model.retrieval import RetrievalService

log = logging.getLogger(__name__)

retrieval = RetrievalService()

class LeagueController(BaseController):
    def _get_stages(self):
        stages = []
        current_stage = 0

        while True:
            arg_name = 'stage_' + str(current_stage)
            if arg_name not in request.urlvars:
                break

            stages.append(request.urlvars[arg_name])
            current_stage += 1

        return stages

    def _make_breadcrumbs(self, league, stages, match=None, game=None):
        crumbs = []
        crumbs.append( (league.name_key, league.name) )

        for stage in stages:
            crumbs.append( (stage.name_key, stage.name) )

        if match:
            key = match.team_one.name_key + '-v-' + match.team_two.name_key
            name = match.team_one.name + ' vs ' + match.team_two.name
            crumbs.append( (key, name) )

        if game:
            game_number = str(game.game_number)
            crumbs.append( ('Set' + game_number, 'Set ' + game_number) )

        return crumbs


    def stage(self):
        league_name = request.urlvars['league']
        stage_names = self._get_stages()

        league, stages = retrieval.stage(league_name,
                stage_names)

        c.league = league
        c.stages = stages
        if len(stages) == 0:
            c.current_stage = c.league
        else:
            c.current_stage = c.stages[-1]

        c.child_stages = c.current_stage.stages.values()
        c.child_stages.sort(key=lambda x: (x.start_date, x.name))

        c.stage_path = [x.name_key for x in stages]

        c.breadcrumbs = self._make_breadcrumbs(league, stages)

        return render('stage.mako')
        
    def match(self):
        league_name = request.urlvars['league']
        stage_names = self._get_stages()
        team_one = request.urlvars['team_one']
        team_two = request.urlvars['team_two']

        league, stages, match = retrieval.match(
            league_name, stage_names, team_one, team_two)

        c.league = league
        c.stages = stages
        c.match = match
        c.current_stage = c.stages[-1]
        c.stage_path = [x.name_key for x in stages]
        c.breadcrumbs = self._make_breadcrumbs(league, stages, match)

        return render('match.mako')
    
    def _find_match_format(self, stages):
        for stage in reversed(stages):
            if stage.format is not None:
                return stage.format

    def view(self):
        league_name = request.urlvars['league']
        stage_names = self._get_stages()
        team_one = request.urlvars['team_one']
        team_two = request.urlvars['team_two']
        game_number = int(request.urlvars['game_number'])

        league, stages, match, game = retrieval.game(
            league_name, stage_names, team_one, team_two, game_number)

        c.league = league
        c.stages = stages
        c.stage_path = [x.name_key for x in stages]
        c.current_stage = stages[-1]
        c.match = match
        c.game_number = game_number

        c.breadcrumbs = self._make_breadcrumbs(league, stages, match, game)

        format = self._find_match_format(stages)
        c.total_games = format['number_of_games']

        if match.winner:
            c.games_played = match.winner_score + match.loser_score
        else:
            c.games_played = len(match.games)

        if game_number > c.games_played and game_number <= c.total_games:
            return render('game_not_necessary.mako')

        if game:
            c.game = game
            return render('view.mako')
        else:
            return render('game_not_available.mako')
                

        return render('view.mako')
